#include "mainwindow.h"
#include <QMessageBox.h>
#include "spreadsheet.h"
#include <QTableWidget.h>
#include "QLabel.h"
#include "QFileDialog.h"
#include "QEvent.h"
#include "finddialog.h"
#include "GoToCellDialog.h"
#include "QSettings.h"
#include "QCoreApplication.h"

mainwindow::mainwindow(QWidget *parent)
	: QMainWindow(parent)
{
	ui.setupUi(this);
	//setAttribute(Qt::WA_DeleteOnClose);// 告诉框架，在关闭窗口时将其删除
	readSettings();
	m_pSpreadsheet = new Spreadsheet(this);
	setCentralWidget(m_pSpreadsheet);

	createActions();
	createMenus();
	createToolBars();
	createStatusBars();
	createDialogs();

	
}

mainwindow::~mainwindow()
{

}

void mainwindow::closeEvent(QCloseEvent *event)
{
	//QMessageBox::information(this,"infor","want to close");
	printf("print to where");
	if(okToContinue()){
		writeSettings();
		event->accept();
	}
	else{
		event->ignore();
	}
}

void mainwindow::createActions()
{
	m_pNewAction = new QAction(tr("&New"),this);
	m_pNewAction->setIcon(QIcon(":/mainwindow/images/new3.png"));
	m_pNewAction->setShortcut(QKeySequence::New);
	m_pNewAction->setStatusTip(tr("Create a new spreadsheet file"));
	QObject::connect(m_pNewAction,SIGNAL(triggered()),this,SLOT(slotNewFile()));

	m_pOpenAction = new QAction(tr("&Open"),this);
	m_pOpenAction->setIcon(QIcon(":/mainwindow/images/open.png"));
	m_pOpenAction->setShortcut(QKeySequence::Open);
	m_pOpenAction->setStatusTip(tr("Open a spreadsheet file"));
	QObject::connect(m_pOpenAction,SIGNAL(triggered()),this,SLOT(slotOpenFile()));

	m_pSaveAction = new QAction(tr("&Save"),this);
	m_pSaveAction->setIcon(QIcon(":/mainwindow/images/save.png"));
	m_pSaveAction->setShortcut(QKeySequence::Save);
	m_pSaveAction->setStatusTip(tr("Save a spreadsheet file"));
	QObject::connect(m_pSaveAction,SIGNAL(triggered()),this,SLOT(slotSaveFile()));
	
	m_pSaveAsAction = new QAction(tr("Save &As..."),this);
	m_pSaveAsAction->setShortcut(QKeySequence::SaveAs);
	m_pSaveAsAction->setStatusTip(tr("Save as a spreadsheet file"));
	QObject::connect(m_pSaveAsAction,SIGNAL(triggered()),this,SLOT(slotSaveAsFile()));
	
	for(unsigned int i=0; i<MaxRecentFiles; i++){
		m_pRecentFileActions[i] = new QAction(this);
		m_pRecentFileActions[i]->setVisible(false);
		QObject::connect(m_pRecentFileActions[i],SIGNAL(triggered()),
			this,SLOT(slotOpenRecentFile()));
	}

	m_pExitAction = new QAction(tr("E&xit"),this);
	m_pExitAction->setShortcut(tr("Ctrl+Q"));
	m_pExitAction->setStatusTip(tr("Exit the program"));
	QObject::connect(m_pExitAction,SIGNAL(triggered()),this,SLOT(slotExitAction()));
	
	m_pCutAction = new QAction(tr("&Cut"),this);
	m_pCutAction->setIcon(QIcon(":/mainwindow/images/cut.png"));
	m_pCutAction->setShortcut(QKeySequence::Cut);
	m_pCutAction->setStatusTip(tr("Cut the selection"));
	QObject::connect(m_pCutAction,SIGNAL(triggered()),this,SLOT(slotCutAction()));

	m_pCopyAction = new QAction(tr("&Copy"),this);
	m_pCopyAction->setIcon(QIcon(":/mainwindow/images/copy.png"));
	m_pCopyAction->setShortcut(QKeySequence::Copy);
	m_pCopyAction->setStatusTip(tr("Copy the selection"));
	QObject::connect(m_pCopyAction,SIGNAL(triggered()),this,SLOT(slotCopyAction()));

	m_pPasteAction = new QAction(tr("&Paste"),this);
	m_pPasteAction->setIcon(QIcon(":/mainwindow/images/paste.png"));
	m_pPasteAction->setShortcut(QKeySequence::Paste);
	m_pPasteAction->setStatusTip(tr("Paste"));
	QObject::connect(m_pPasteAction,SIGNAL(triggered()),this,SLOT(slotPasteAction()));

	m_pDeleteAction = new QAction(tr("&Delete"),this);
	m_pDeleteAction->setShortcut(QKeySequence::Delete);
	m_pDeleteAction->setStatusTip(tr("Delete"));
	QObject::connect(m_pDeleteAction,SIGNAL(triggered()),this,SLOT(slotDeleteAction()));

	m_pSelectRawAction = new QAction(tr("&Raw"),this);
	m_pSelectRawAction->setStatusTip(tr("Selete the Raw"));
	QObject::connect(m_pSelectRawAction,SIGNAL(triggered()),this,SLOT(slotSelectRawAction()));

	m_pSelectColAction = new QAction(tr("&Column"),this);
	m_pSelectColAction->setStatusTip(tr("Selete the Column"));
	QObject::connect(m_pSelectColAction,SIGNAL(triggered()),this,SLOT(slotSelectColAction()));

	m_pSelectAllAction = new QAction(tr("&All"),this);
	m_pDeleteAction->setShortcut(QKeySequence::SelectAll);
	m_pSelectAllAction->setStatusTip(tr("Selete All"));
	QObject::connect(m_pSelectAllAction,SIGNAL(triggered()),this,SLOT(slotSelectAllAction()));
	
	m_pFindAction = new QAction(tr("&Find..."),this);
	m_pFindAction->setIcon(QIcon(":/mainwindow/images/find.png"));
	m_pFindAction->setShortcut(QKeySequence::Find);
	m_pFindAction->setStatusTip(tr("Find"));
	QObject::connect(m_pFindAction,SIGNAL(triggered()),this,SLOT(slotFindAction()));
	
	m_pGoToCellAction = new QAction(tr("&Go to Cell..."),this);
	m_pGoToCellAction->setIcon(QIcon(":/mainwindow/images/goto.png"));
	m_pGoToCellAction->setStatusTip(tr("To to Cell"));
	QObject::connect(m_pGoToCellAction,SIGNAL(triggered()),this,SLOT(slotGoToCellAction()));
	
	m_pRecalculateAction = new QAction(tr("&Recalculate"),this);
	m_pRecalculateAction->setShortcut(tr("F9"));
	m_pRecalculateAction->setStatusTip(tr("Recalculate"));
	QObject::connect(m_pRecalculateAction,SIGNAL(triggered()),this,SLOT(slotRecalculateAction()));

	m_pSortAction = new QAction(tr("&Sort"),this);
	m_pSortAction->setStatusTip(tr("Sort"));
	QObject::connect(m_pSortAction,SIGNAL(triggered()),this,SLOT(slotSortAction()));
	
	m_pShowGridAction = new QAction(tr("&Show Grid"),this);
	m_pShowGridAction->setStatusTip(tr("Show Grid"));
	m_pShowGridAction->setCheckable(true);
	QObject::connect(m_pShowGridAction,SIGNAL(triggered(bool)),this,SLOT(slotShowGridAction(bool)));

	m_pAutoRecalAction = new QAction(tr("&Auto Recalculate"),this);
	m_pAutoRecalAction->setStatusTip(tr("Auto Recalculate"));
	m_pAutoRecalAction->setCheckable(true);
	QObject::connect(m_pAutoRecalAction,SIGNAL(triggered(bool)),this,SLOT(slotAutoRecalAction(bool)));

	m_pAboutAction = new QAction(tr("&About"),this);
	m_pAboutAction->setStatusTip(tr("About"));
	QObject::connect(m_pAboutAction,SIGNAL(triggered()),this,SLOT(slotAboutAction()));

	m_pAboutQtAction = new QAction(tr("About &Qt"),this);
	m_pAboutQtAction->setStatusTip(tr("About Qt"));
	QObject::connect(m_pAboutQtAction,SIGNAL(triggered()),qApp,SLOT(aboutQt()));


}

void mainwindow::createMenus()
{
	m_pFileMenu = menuBar()->addMenu(tr("&File"));
	m_pFileMenu->addAction(m_pNewAction);
	m_pFileMenu->addAction(m_pOpenAction);
	m_pFileMenu->addAction(m_pSaveAction);
	m_pFileMenu->addAction(m_pSaveAsAction);
	m_pSeparatorAtcion = m_pFileMenu->addSeparator();
	for(unsigned int i=0; i<MaxRecentFiles; i++)
		m_pFileMenu->addAction(m_pRecentFileActions[i]);
	m_pFileMenu->addSeparator();
	m_pFileMenu->addAction(m_pExitAction);

	m_pEditMenu = menuBar()->addMenu(tr("&Edit"));
	m_pEditMenu->addAction(m_pCutAction);
	m_pEditMenu->addAction(m_pCopyAction);
	m_pEditMenu->addAction(m_pPasteAction);
	m_pEditMenu->addAction(m_pDeleteAction);
	m_pSelectSubMenu = m_pEditMenu->addMenu(tr("&Select"));
	m_pSelectSubMenu->addAction(m_pSelectRawAction);
	m_pSelectSubMenu->addAction(m_pSelectColAction);
	m_pSelectSubMenu->addAction(m_pSelectAllAction);
	m_pEditMenu->addSeparator();
	m_pEditMenu->addAction(m_pFindAction);
	m_pEditMenu->addAction(m_pGoToCellAction);

	m_pToolsMenu = menuBar()->addMenu(tr("&Tools"));
	m_pToolsMenu->addAction(m_pRecalculateAction);
	m_pToolsMenu->addAction(m_pSortAction);

	m_pOptionsMenu = menuBar()->addMenu(tr("Options"));
	m_pOptionsMenu->addAction(m_pShowGridAction);
	m_pOptionsMenu->addAction(m_pAutoRecalAction);

	m_pHelpMenu = menuBar()->addMenu(tr("&Help"));
	m_pHelpMenu->addAction(m_pAboutAction);
	m_pHelpMenu->addAction(m_pAboutQtAction);




}

void mainwindow::createToolBars()
{
	
	m_pFileToolBar = addToolBar(tr("&File"));
	m_pFileToolBar->addAction(m_pNewAction);
	m_pFileToolBar->addAction(m_pOpenAction);
	m_pFileToolBar->addAction(m_pSaveAction);

	m_pEditToolBar = addToolBar(tr("&Edit"));
	m_pEditToolBar->addAction(m_pCutAction);
	m_pEditToolBar->addAction(m_pCopyAction);
	m_pEditToolBar->addAction(m_pPasteAction);
	m_pEditToolBar->addSeparator();
	m_pEditToolBar->addAction(m_pFindAction);
	m_pEditToolBar->addAction(m_pGoToCellAction);
}

void mainwindow::createStatusBars()
{
	m_pLocationLabel = new QLabel(" W999 ");
	m_pLocationLabel->setAlignment(Qt::AlignCenter);
	m_pLocationLabel->setMinimumSize(m_pLocationLabel->sizeHint());

	m_pFormulaLabel = new QLabel;
	m_pFormulaLabel->setIndent(3);// 缩进

	statusBar()->addWidget(m_pLocationLabel);
	statusBar()->addWidget(m_pFormulaLabel,3);

	QObject::connect(m_pSpreadsheet,SIGNAL(currentCellChanged(int,int,int,int)),
		this,SLOT(updateStatusBar()));
	QObject::connect(m_pSpreadsheet,SIGNAL(modified()),
		this,SLOT(spreadsheetModifyed()));

	slotUpdateStatusBar();
}

void mainwindow::createDialogs()
{
	m_pFindDialog = new FindDialog(this);
	QObject::connect(m_pFindDialog,SIGNAL(findNext(const QString& str, Qt::CaseSensitivity cs)),
					m_pSpreadsheet,SLOT(findNext(const QString& str, Qt::CaseSensitivity cs)));
	QObject::connect(m_pFindDialog,SIGNAL(findPrevious(const QString& str, Qt::CaseSensitivity cs)),
		m_pSpreadsheet,SLOT(findPrevious(const QString& str, Qt::CaseSensitivity cs)));
}

bool mainwindow::okToContinue()
{
	if(isWindowModified())
	{
		int r = QMessageBox::warning(this,tr("SpreedSheet"),
			tr("The Document has been modified.\n"
			"Do you want to save your change?"),
			QMessageBox::Yes|QMessageBox::No|QMessageBox::Cancel);
		if(r == QMessageBox::Yes)
			return slotSaveFile();
		else if(r == QMessageBox::Cancel)
			return false;
	}
	return true;
}

bool mainwindow::loadFile(const QString& filename)
{
	if(!m_pSpreadsheet->readFile(filename))
	{
		statusBar()->showMessage(tr("Loading canceled"),2000);
		return false;
	}
	setCurrentFile(filename);
	statusBar()->showMessage(tr("File Loaded"),2000);
	return true;
}

bool mainwindow::saveFile(const QString& filename)
{
	if(!m_pSpreadsheet->writeFile(filename))
	{
		statusBar()->showMessage(tr("Saving file canceled"),2000);
		return false;
	}
	setCurrentFile(filename);
	statusBar()->showMessage(tr("File Saved"),2000);
	return true;
}

void mainwindow::setCurrentFile(const QString& fileName)
{
	m_curFile = fileName;
	setWindowModified(false);
	QString shownName = tr("Untitled");
	if(!m_curFile.isEmpty()){
		shownName = strippedName(m_curFile);
		
	}
	setWindowTitle(tr("%1[*] - %2")
					.arg(shownName)
					.arg(tr("Spreadsheet")));
}

QString mainwindow::strippedName(const QString& fullFileName)
{
	return QFileInfo(m_curFile).fileName();
}

void mainwindow::readSettings()
{
	QSettings settings("QtStudyTest","Spreadsheet");

	QString appversion = settings.value("application version",true).toString();
	//QMessageBox::information(this,"info",appversion);
}
void mainwindow::writeSettings()
{
	QSettings settings("QtStudyTest","Spreadsheet");

	settings.setValue("application version", "V1.0.0");
}

void mainwindow::updateRecentFileActions()
{
	QMutableStringListIterator it(m_recentFiles);
	while(it.hasNext()){
		if(!QFile::exists(it.next()))
			it.remove();
	}
	for(int i=0; i<MaxRecentFiles;i++){
		if(i<m_recentFiles.count()){
			QString text = tr("&%1 %2")
							.arg(i+1)
							.arg(strippedName(m_recentFiles[i]));
			m_pRecentFileActions[i]->setText(text);
			m_pRecentFileActions[i]->setData(m_recentFiles[i]);
			m_pRecentFileActions[i]->setVisible(true);
		}
		else{
			m_pRecentFileActions[i]->setVisible(false);
		}
	}
	m_pSeparatorAtcion->setVisible(!m_recentFiles.isEmpty());
}
void mainwindow::slotNewFile()
{
	//if(okToContinue())
	//{
		//mainwindow *w = new mainwindow;
		//w->show();
		m_pSpreadsheet->clear();
	//}
	
}

void mainwindow::slotOpenFile()
{
	if(okToContinue())
	{
		QString fileName = QFileDialog::getOpenFileName(this,tr("Open Spreadsheet"),"",tr("Spreadsheet files (*.sp)"));
		if(!fileName.isEmpty())
			loadFile(fileName);
	}
}

bool mainwindow::slotSaveFile()
{
	if(m_curFile.isEmpty())
		return slotSaveAsFile();
	else
		return saveFile(m_curFile);
}

bool mainwindow::slotSaveAsFile()
{
	QString fileName = QFileDialog::getSaveFileName(this,
		tr("Save Spreadsheet"),
		".",
		tr("Spreadsheet files (*.sp)"));
	if(fileName.isEmpty())
		return false;
	return saveFile(fileName);
}

void mainwindow::slotOpenRecentFile()
{
	if(okToContinue()){
		QAction *action = qobject_cast<QAction*>(sender());
		if(action)
			loadFile(action->data().toString());
	}
}

void mainwindow::slotExitAction()
{
	//QApplication::closeAllWindows();
	close();
}

void mainwindow::slotCutAction()
{

}
void mainwindow::slotCopyAction()
{
	m_pSpreadsheet->copy();
}
void mainwindow::slotPasteAction()
{

}
void mainwindow::slotDeleteAction()
{

}
void mainwindow::slotSelectRawAction()
{

}
void mainwindow::slotSelectColAction()
{

}

void mainwindow::slotSelectAllAction()
{

}

void mainwindow::slotFindAction()
{
	m_pFindDialog->show();
	m_pFindDialog->raise();
	m_pFindDialog->activateWindow();
}
void mainwindow::slotGoToCellAction()
{
	GoToCellDialog dlg(this);
	if(dlg.exec()){
		QString str = dlg.getEditText();
		m_pSpreadsheet->setCurrentCell(str.mid(1).toInt()-1,
								str[0].unicode()-'A');
	}
}

void mainwindow::slotRecalculateAction()
{

}

void mainwindow::slotSortAction()
{

}

void mainwindow::slotShowGridAction(bool val)
{

}
void mainwindow::slotAutoRecalAction(bool val)
{

}

void mainwindow::slotAboutAction()
{
	QMessageBox::about(this,
		tr("About Spreadsheet"),
		tr("<h2>Spreadsheet 1.1</h2>"
		"<p>Copyright &Copy; 2016 Software Inc."
		"</p>Spreadsheet is a small application"));
}

void mainwindow::slotUpdateStatusBar()
{
	m_pLocationLabel->setText(tr("ldkfj"));
	m_pFormulaLabel->setText(tr("dlkfjdf"));
}

void mainwindow::slotSpreadsheetModifyed()
{
	setWindowModified(true);
	slotUpdateStatusBar();
}

